package com.yuncheng.spcyApi.flowController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.flow.SpBzFlowConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.SpcyZjFlowConstant;
import com.yuncheng.spcyApi.constant.flow.YpscFlowConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.spcyApi.entity.SpcySqsxJob;
import com.yuncheng.spcyApi.flowService.SpBzFlowService;
import com.yuncheng.spcyApi.mapper.SpcyFlowMapper;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcySqsxBaiscService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.flow.YpscFlowVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyFlowVo;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

//@Api(tags = "审评查验-补正流程接口")
@RestController
@RequestMapping("/api/spzx-spcy/flow-spbzlc")
public class SpBzFlowController {
    private static final Logger log = LoggerFactory.getLogger(SpBzFlowController.class);

    @Resource
    private SpBzFlowConstant spBzFlowConstant;

    @Resource
    private SpcyFlowMapper spcyFlowMapper;

    @Resource
    private SpBzFlowService spBzFlowService;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    private BusService busService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Log(title = "发起补正流程")
    @ApiOperation(value = "发起补正流程")
    @GetMapping(value = "initBzFlow")
    public HttpResult<?> initBzFlow(@RequestParam("sqsxid")String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("参数丢失，请联系管理员");
        }
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        Result result = spBzFlowService.initJob(sqsxid, currentUser);
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }else {
            spBzFlowService.stopSpcyFlowNodeStart(sqsxid); // 暂停开始时间

            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
            if (sqsx != null){

                SpcySqsxJob job = (SpcySqsxJob) result.getResult();
                if (job != null) {
                    // 发送短信
                    String smsLog = busService.getNextNodeSmsContent(sqsx, SpBzFlowConstant.FLOW_NAME, job.getFhjmc());
                    busService.sendSmsToNodeDbr(job.getFdbrid(), job.getFhjmc(),smsLog);
                }

                sqsx.setFspbzlczt(SpcyZjFlowConstant.SP_Bz_FLOW_ZT); // 办理中
                spcySqsxBaiscService.updateById(sqsx);

                String logCon = "发起补正流程：[申请事项]为【"+sqsx.getFsxmc()+"】;\n[受理编号]为【"+sqsx.getFslbh()+"】;";
                spcyLogService.addLogs(YpscFlowConstant.HJMC_FAZZ,logCon,sqsxid, SpcyConstant.LOGS_SYS_TYPE_TJ,SpcyConstant.LOGS_SYS_TYPE_TJ);
            }
        }

        return HttpResult.ok("发起成功");
    }

    @Log(title = "发起补正流程-书面审查意见")
    @ApiOperation(value = "发起补正流程-书面审查意见")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "sqsxid",value = "申请事项id"),
            @ApiImplicitParam(name = "smscyj",value = "书面审查意见")
    })
    @PostMapping(value = "initBzFlowWithSmscyj")
    public HttpResult<?> initBzFlowWithSmscyj(@RequestBody Map<String,String> map){
        String sqsxid = map.get("sqsxid");
        String smscyj = map.get("smscyj");
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("申请事项参数丢失，请联系管理员");
        }
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("当前登录已失效，请重新登录");
        }

        Result result = spBzFlowService.initSmscyjJob(sqsxid,smscyj, currentUser);
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }else {
            spBzFlowService.stopSpcyFlowNodeStart(sqsxid); // 暂停开始时间

            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
            if (sqsx != null){

                SpcySqsxJob job = (SpcySqsxJob) result.getResult();
                if (job != null) {
                    // 发送短信
                    String smsLog = busService.getNextNodeSmsContent(sqsx, SpBzFlowConstant.FLOW_NAME, job.getFhjmc());
                    busService.sendSmsToNodeDbr(job.getFdbrid(), job.getFhjmc(),smsLog);
                }

                sqsx.setFspbzlczt(SpcyZjFlowConstant.SP_Bz_FLOW_ZT); // 办理中
                spcySqsxBaiscService.updateById(sqsx);

                String logCon = "发起补正流程：[申请事项]为【"+sqsx.getFsxmc()+"】;\n[受理编号]为【"+sqsx.getFslbh()+"】;";
                spcyLogService.addLogs(YpscFlowConstant.HJMC_FAZZ,logCon,sqsxid, SpcyConstant.LOGS_SYS_TYPE_TJ,SpcyConstant.LOGS_SYS_TYPE_TJ);
            }
        }

        return HttpResult.ok("发起成功");
    }

    @Log(title = "撤回流程")
    @ApiOperation(value = "撤回流程")
    @GetMapping(value = "returnSpBzFlow")
    public HttpResult<?> returnSpBzFlow(@RequestParam("jobid")String jobid,
                                        @RequestParam(value = "opinion",defaultValue = "")String opinion){
        if (StringUtils.isBlank(jobid)){
            return HttpResult.error("参数丢失，请联系管理员");
        }
        Result result = spBzFlowService.returnSpBzFlow(jobid,opinion);
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }

        return HttpResult.ok("撤回成功");
    }

    @Log(title = "终止流程")
    @ApiOperation(value = "终止流程")
    @GetMapping(value = "endFlowJob")
    public HttpResult<?> endFlowJob(@RequestParam("jobid") String jobid){

        Result result = spBzFlowService.endFlowJob(jobid);
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }

        return HttpResult.ok("终止成功");
    }

    @Log(title = "获取补正流程最后一个环节的办理意见")
    @ApiOperation(value = "获取补正流程最后一个环节的办理意见")
    @GetMapping(value = "getLastNodeBlyj")
    public HttpResult getLastNodeBlyj(@RequestParam(value = "sqsxid",defaultValue = "") String sqsxid){
        Map resultMap = new HashMap();

        String blyj = spBzFlowService.getLastNodeBlyj(sqsxid);

        resultMap.put("blyj", blyj);

        return HttpResult.ok(resultMap);
    }

    /**
     * 流程流程监控分页查询
     * @param spcyFlowVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @Log(title = "流程监控-分页查询")
    @ApiOperation(value = "流程监控-分页查询")
    @GetMapping("flowJkPage")
    public HttpResult<?> flowJkPage(
            SpcyFlowVo spcyFlowVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser,
            OrderItemVo orderItemVo){
        CurrentUserVo user = GetCurrentUserUtils.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<SpcyFlowVo> page = new Page<>(pageNo, pageSize);
        spcyFlowVo.setFlcmc(spBzFlowConstant.getFlowName());
        IPage<SpcyFlowVo> list = spcyFlowMapper.flowJkPage(page,onlyCurrentUser,user,spcyFlowVo,orderItemVo);
        return HttpResult.ok(list);
    }

    /**
     * 流程列表分页查询
     * @param spcyFlowVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @Log(title = "流程列表-分页查询")
    @ApiOperation(value = "流程列表-分页查询")
    @GetMapping("flowJobPage")
    public HttpResult<?> flowJobPage(
            SpcyFlowVo spcyFlowVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "true") boolean onlyCurrentUser,
            OrderItemVo orderItemVo){
        CurrentUserVo user = GetCurrentUserUtils.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<SpcyFlowVo> page = new Page<>(pageNo, pageSize);
        spcyFlowVo.setFlcmc(spBzFlowConstant.getFlowName());
        IPage<SpcyFlowVo> list = spcyFlowMapper.flowJkPage(page,onlyCurrentUser,user,spcyFlowVo,orderItemVo);
        return HttpResult.ok(list);
    }

    /**
     * 补正流程保存接口
     */
    @Log(title = "补正流程保存接口")
    @ApiOperation(value = "补正流程保存接口")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody YpscFlowVo ypscFlowVo) {
        String submitType = YpscFlowConstant.SUBMIT_TYPE_SAVE; // 保存
        String jobId = ypscFlowVo.getJobid(); // 当前流程任务id
        String sqsxid = ypscFlowVo.getSqsxid(); // 当前申请事项id
        String opinion = ypscFlowVo.getOpinion(); // 办理意见

        /*if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("申请事项id参数丢失，请联系管理员");
        }*/
        if (StringUtils.isBlank(jobId)){
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }

        // 流程处理
        Result httpResult = spBzFlowService.handleFlow(ypscFlowVo, null, jobId, sqsxid, submitType, opinion);
        if (!httpResult.isSuccess()){
            return HttpResult.error(httpResult.getMessage());
        }

        Map map = new HashMap();
        HttpResult<Object> res = new HttpResult<>(true);
        res.setMessage("保存成功");
        Map jobConcernByJobId = busService.getJobConcernByJobId(jobId);
        map.putAll(jobConcernByJobId);

        res.setResult(map);
        return res;
    }

    /**
     * 补正流程提交接口
     */
    @Log(title = "补正流程提交接口")
    @ApiOperation(value = "补正流程提交接口")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody YpscFlowVo ypscFlowVo) {
        String submitType = YpscFlowConstant.SUBMIT_TYPE_SUBMIT; // 提交

        String jobId = ypscFlowVo.getJobid();
        String sqsxid = ypscFlowVo.getSqsxid();
        String opinion = ypscFlowVo.getOpinion();

        /*if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("申请事项id参数丢失，请联系管理员");
        }*/

        if (StringUtils.isBlank(jobId)){
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }

       /* if (StringUtils.isBlank(opinion)){
            return HttpResult.error("请填写办理意见");
        }*/

        SpcySqsxJob nowJob = null;

        Result httpResult1 = spBzFlowService.handleFlow(ypscFlowVo, nowJob, jobId, sqsxid, submitType, opinion);
        if (!httpResult1.isSuccess()){
            return HttpResult.error(httpResult1.getMessage());
        }

        return HttpResult.ok("提交成功");
    }

    /**
     * 查询当前流程任务详情-通过当前流程任务id
     */
    @Log(title = "查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiImplicitParam(value = "jobid",name = "流程任务id",required = true)
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam("jobid")String jobid){
        if (StringUtils.isBlank(jobid)){
            return HttpResult.error("流程任务id不能为空");
        }
        Map map = spBzFlowService.getJobConcernByJobId(jobid);
        return HttpResult.ok(map);
    }
}
